/*
 * @Desc:请求配置
 * @author cheegon
 * @date 2022/7/25  10:54
**/
import axios from 'axios'
import { Message } from 'element-ui'
import store from '../store'
import { curr_env } from './envConfig'
import { getToken } from '@/config/authConfig.js'

// 创建axios实例
const service = axios.create({
    baseURL: curr_env.baseUrl,
    timeout: 15000
})

// 添加请求拦截器
service.interceptors.request.use(config => {
    // 让每个请求携带自定义token 请根据实际情况自行修改
    // config.headers.Authorization = getToken()||''
    config.headers.Authorization = store.state.token || ''
    return config
}, error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
})

// 添加响应拦截器
service.interceptors.response.use(
    response => {

        // code为非200是抛错 可结合自己业务进行修改
        const { code, message } = response.data;

        if (response.data instanceof Blob) {
            return response.data
        } else {
            if (code === 200) return response.data;
            else if (code === 401) {
                Message({
                    message: '登录超时，请重新登录',
                    type: 'error',
                    duration: 2000,
                    showClose: true,
                    offset: 350
                })
                store.dispatch('fedLogout').then(() => {
                    location.reload() // 为了重新实例化vue-router对象 避免bug
                })
            } else {
                Message({
                    message,
                    type: 'error',
                    duration: 2000,
                    showClose: true,
                    offset: 350
                })
                return Promise.reject(response.data);
            }
        }
    },
    error => {
        console.log('err' + error)// for debug
        Message({
            message: error.message,
            type: 'error',
            duration: 2000,
            showClose: true,
            offset: 350
        })
        return Promise.reject(error)
    }
)

export default service
